package com.bakend.common.config.security.handler;

import com.alibaba.fastjson.JSON;
import com.bakend.common.R;
import com.bakend.common.utils.HttpUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 匿名未登录的请求，会进入这里进行处理
 */
@Component
public class CustomerAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        //设置response状态码，返回错误信息等
        sendUnauthenticationMsg(response);
    }
    private void sendUnauthenticationMsg(HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Origin", HttpUtils.getOrigin());
        R invalid_token = R.Error(HttpStatus.UNAUTHORIZED.value(), "invalid token");
        String json = JSON.toJSONString(invalid_token);
        response.getWriter().print(json);
    }
}
